﻿using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;
using Google.Apis.Plus.v1;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Microsoft.AspNet.Membership.OpenAuth;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using WeSpot.Models;

namespace WeSpot.Controllers
{

    [Authorize]
    public class AccountController : Controller
    {
        //
        // GET: /Account/Index

        public ActionResult Index()
        {
            
            return View();
        }

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login()
        {
            
            return View();
        }

        //
        // POST: /Account/Login

        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            
            return RedirectToAction("Index", "Home");
        }
        /*
        private void  externalLogout() 
        {
    var url, params;
    if (accountType== "facebook") {
        url = "https://www.facebook.com/logout.php";
        params = {
            next: redirectUrl,
            access_token: encodeURIComponent(accessToken)
        };
        performCallLogout(url, params, accountType);
    } else if (accountType== "google") {
        url = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout";
        params = {
            next: redirectUrl
        }
        performCallLogout(url, params, accountType);
    } else if (accountType == "microsoft") {
        url = "https://login.live.com/oauth20_logout.srf";
        params = {
            clientId: clientID,
            redirectUrl: redirectUrl
        }
        performCallLogout(url, params, accountType);
    }
}

function performCallLogout(url, params, accountType) {
    if (accountType == "facebook") {
        window.location.href = url + "?next=" + params.next + "&access_token=" + params.access_token;
    } else if (accountType == "google") {
        window.location.href = url + "?continue=" + params.next;
    } else if (accountType == "microsoft") {
        window.location.href = url + "?client_id=" + params.clientId + "&redirect_url=" + params.redirectUrl;
    }
}*/
        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, userIsOnline: true);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        [AllowAnonymous]
        public ActionResult Dummy(string provider)
        {
            
            return RedirectToAction("Dummy", "Globalization");
            //return RedirectToAction("Index", "Secure");
            //return Redirect(Url.Action("Index", "Secure"));

        }


        // Stores token response info such as the access token and refresh token.
        private TokenResponse token;

        // Used to peform API calls against Google+.
        private PlusService ps = null;
        public static ClientSecrets secrets = new ClientSecrets()
        {
            ClientId = "392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com",
            ClientSecret = "IPLjbx9AmTrO4BGLq0GW-5nH"
        };


        [AllowAnonymous]
        public ActionResult ExternalLogin(string provider)
        {

            if (provider.Equals("google"))
            {
                //https://wespot-arlearn.appspot.com/Login.html?scope=profile+email&response_type=code&redirect_uri=http%3A%2F%2Fibl.exactls.com%2FAccount%2FExternalLoginCallback&client_id=TestWeSpot01
                // just pass a provider to make it work
                // OpenAuth.RequestAuthentication(provider, Url.Action("ExternalLoginCallback"));
                string requestUrl = "https://accounts.google.com/o/oauth2/auth?scope=email%20profile&state=%2Fprofile&redirect_uri=http://ibl.exactls.com/Account/oauth2callback&response_type=code&client_id=392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com&approval_prompt=force&include_granted_scopes=true";


                RestClient rc = new RestClient();
                RestRequest request = new RestRequest(requestUrl, Method.GET);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("x-li-format", "json");
                request.RequestFormat = DataFormat.Json;

                //send the request, and check the response.
                RestResponse restResponse = (RestResponse)rc.Execute(request);
                if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

                //if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }
                return Redirect(restResponse.ResponseUri.ToString());
            }

            if (provider.Equals("facebook"))
            {
                string requestUrl = "https://www.facebook.com/dialog/oauth?" +
                                    "client_id=" + "1409686772621514" +
                                    "&display = popup"+
                                    "&response_type = token" +
                                    "&redirect_uri=" + "http://ibl.exactls.com/Account/oauth2callbackFacebook";
                RestClient rc = new RestClient();
                RestRequest request = new RestRequest(requestUrl, Method.GET);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("x-li-format", "json");
                request.RequestFormat = DataFormat.Json;

                //send the request, and check the response.
                RestResponse restResponse = (RestResponse)rc.Execute(request);
                if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

                //if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }
                return Redirect(restResponse.ResponseUri.ToString());

                //return RedirectToAction("Login", "Account");

            }
            if (provider.Equals("WeSpot"))
            {
                /*string requestUrl = "";
                return RedirectToAction("Login", "Account");*/
                string requestUrl = "https://wespot-arlearn.appspot.com/Login.html?" +
                                    "client_id=" + "313313" +
                                    "&redirect_uri=" + "http://ibl.exactls.com/Account/oauth2callbackWeSpot&response_type=code&scope=profile+email";
                RestClient rc = new RestClient();
                RestRequest request = new RestRequest(requestUrl, Method.GET);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("x-li-format", "json");
                request.RequestFormat = DataFormat.Json;

                //send the request, and check the response.
                RestResponse restResponse = (RestResponse)rc.Execute(request);
                if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

                //if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }
                return Redirect(restResponse.ResponseUri.ToString());



            }
            else
                return RedirectToAction("Login", "Account");
            
        }
        /**
         Google
            CLIENT ID 392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com 
            EMAIL ADDRESS  392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b@developer.gserviceaccount.com  
            CLIENT SECRET  IPLjbx9AmTrO4BGLq0GW-5nH 
            REDIRECT URIS  https://ibl.exacts.com/oauth2callback
            JAVASCRIPT ORIGINS https://ibl.exacts.com     
         */
        //Task<Google.Apis.Auth.OAuth2.Web.AuthorizationCodeWebApp.AuthResult>
        public static async void GetCredentials(Controller controller, CancellationToken cancellationToken)
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential =  await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,null,
                    
                    "user", CancellationToken.None, new FileDataStore("WeSpot.ListMyLibrary"));
            }

            var result =  await new AuthorizationCodeMvcApp(controller, new Models.AppFlowMetadata()).AuthorizeAsync(cancellationToken);
            if (result.Credential != null)
            {
                var oauthSerivce = new Google.Apis.Oauth2.v2.Oauth2Service(
                new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "WeSpot",
                });

                var userInfo =  oauthSerivce.Userinfo.Get().ExecuteAsync();
            }
        }

        public static GoogleClientSecrets GetClientConfiguration()
        {
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                return GoogleClientSecrets.Load(stream);
            }
        }
        
        public PlusService GetPlusService(TokenResponse credentials)
        {
            IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GetClientConfiguration().Secrets,
                    Scopes = new string[] { PlusService.Scope.PlusLogin }
                });

            UserCredential credential = new UserCredential(flow, "me", credentials);

            return new PlusService(
                new Google.Apis.Services.BaseClientService.Initializer()
                {
                    ApplicationName = "Haikunamatata",
                    HttpClientInitializer = credential
                });
        }

        // Configuration that you probably don't need to change.
        static public string APP_NAME = "Google+ C# Quickstart";


        [AllowAnonymous]
        [HttpGet]
        public ActionResult oauth2callback(string param)
        {
            string authToken = Request.Url.Query.Substring(Request.Url.Query.IndexOf("code=") + 5, Request.Url.Query.IndexOf("scope=") - (Request.Url.Query.IndexOf("code=") + 6));

            // OpenAuth.RequestAuthentication(provider, Url.Action("ExternalLoginCallback"));
            string requestUrl = "https://accounts.google.com/o/oauth2/token";
                //?code=" + authToken + "&client_id=392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com" + "&client_secret=IPLjbx9AmTrO4BGLq0GW-5nH" + "&grant_type=authorization_code" + "&redirect_uri=http://ibl.exactls.com/Account/oauth2callback";
            
            
            //scope=email%20profile&state=%2Fprofile&redirect_uri=http://ibl.exactls.com/Account/oauth2callback&response_type=code&client_id=392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com&approval_prompt=force&include_granted_scopes=true";


            RestClient rc = new RestClient();
            RestRequest request = new RestRequest(requestUrl, Method.POST);
            request.AddParameter("code", authToken, ParameterType.GetOrPost);
            request.AddParameter("client_id", "392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com", ParameterType.GetOrPost);
            request.AddParameter("client_secret", "IPLjbx9AmTrO4BGLq0GW-5nH", ParameterType.GetOrPost);
            request.AddParameter("grant_type", "authorization_code", ParameterType.GetOrPost);
            request.AddParameter("redirect_uri", "http://ibl.exactls.com/Account/oauth2callback", ParameterType.GetOrPost);
        
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            request.RequestFormat = DataFormat.Json;

            //send the request, and check the response.
            RestResponse restResponse = (RestResponse)rc.Execute(request);
            if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

            JObject o = JObject.Parse(restResponse.Content);
            string access_token = (string)o["access_token"];
            string expires_in = (string)o["expires_in"];
            string token_type = (string)o["token_type"];




            string requestUrl1 = "https://www.googleapis.com/plus/v1/people/me?access_token=" + access_token;


            RestClient rc1 = new RestClient();
            RestRequest request1 = new RestRequest(requestUrl1, Method.GET);
            request1.AddHeader("Content-Type", "application/json");
            request1.AddHeader("x-li-format", "json");
            request1.RequestFormat = DataFormat.Json;

            //send the request, and check the response.
            RestResponse restResponse1 = (RestResponse)rc1.Execute(request1);
            if (!restResponse1.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

            JObject o1 = JObject.Parse(restResponse1.Content);
            string oauthID = (string)o1["id"];
            string UserName = (string)o1["displayName"];

            Session.Add("UserName", UserName);
            Session.Add("ProviderUserId", oauthID);
            Session.Add("Provider", "google");
            Session.Add("oauthID", oauthID);
            Session.Add("oauthProvider", "google");
            Session.Add("OauthIdTOUserName", new Hashtable());
            Session.Add("OauthIdTOProvider", new Hashtable());
            Session.Add("OauthPlusProviderIdTOIcon", new Hashtable());
            FormsAuthentication.SetAuthCookie(oauthID,false );
        
            return Redirect(Url.Action("Index", "Secure"));
            
        }


        [AllowAnonymous]
        [HttpGet]
        public ActionResult oauth2callbackFacebook(string param)
        {
            //https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.1#confirm
            //https://developers.facebook.com/apps/1409686772621514/app-details/
            //wespottest
            //App ID : 1409686772621514
            //App Secret : c727ce18349262d24c091f8aae5a70b0

            string authToken = Request.Url.Query.Substring(Request.Url.Query.IndexOf("code=") + 5, Request.Url.Query.Length - (Request.Url.Query.IndexOf("code=") + 5));
                //Request.Url.Query.Substring(Request.Url.Query.IndexOf("code=") + 5, Request.Url.Query.IndexOf("scope=") - (Request.Url.Query.IndexOf("code=") + 6));

            // OpenAuth.RequestAuthentication(provider, Url.Action("ExternalLoginCallback"));
            string requestUrl = "https://graph.facebook.com/oauth/access_token";

            //?code=" + authToken + "&client_id=392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com" + "&client_secret=IPLjbx9AmTrO4BGLq0GW-5nH" + "&grant_type=authorization_code" + "&redirect_uri=http://ibl.exactls.com/Account/oauth2callback";


            //scope=email%20profile&state=%2Fprofile&redirect_uri=http://ibl.exactls.com/Account/oauth2callback&response_type=code&client_id=392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com&approval_prompt=force&include_granted_scopes=true";


            RestClient rc = new RestClient();
            RestRequest request = new RestRequest(requestUrl, Method.POST);
            request.AddParameter("code", authToken, ParameterType.GetOrPost);
            request.AddParameter("client_id", "1409686772621514", ParameterType.GetOrPost);
            request.AddParameter("client_secret", "c727ce18349262d24c091f8aae5a70b0", ParameterType.GetOrPost);
            //request.AddParameter("grant_type", "authorization_code", ParameterType.GetOrPost);
            request.AddParameter("redirect_uri", "http://ibl.exactls.com/Account/oauth2callbackFacebook", ParameterType.GetOrPost);

            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            request.RequestFormat = DataFormat.Json;

            //send the request, and check the response.
            RestResponse restResponse = (RestResponse)rc.Execute(request);
            if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }


            //access_token={access-token}&expires={seconds-til-expiration}
            string access_token = restResponse.Content.Substring(restResponse.Content.IndexOf("access_token=") + 13, restResponse.Content.IndexOf("&expires=") - 13);
            //JObject o = JObject.Parse(restResponse.Content);
            //string access_token = (string)o["access_token"];
            //string expires_in = (string)o["expires"];
            //string token_type = (string)o["token_type"];




            string requestUrl1 = "https://graph.facebook.com/me?access_token=" + access_token;


            RestClient rc1 = new RestClient();
            RestRequest request1 = new RestRequest(requestUrl1, Method.GET);
            request1.AddHeader("Content-Type", "application/json");
            request1.AddHeader("x-li-format", "json");
            request1.RequestFormat = DataFormat.Json;

            //send the request, and check the response.
            RestResponse restResponse1 = (RestResponse)rc1.Execute(request1);
            if (!restResponse1.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

            JObject o1 = JObject.Parse(restResponse1.Content);
            string oauthID = (string)o1["id"];
            string UserName = (string)o1["name"];

            Session.Add("UserName", UserName);
            Session.Add("ProviderUserId", oauthID);
            Session.Add("Provider", "facebook");
            Session.Add("oauthID", oauthID);
            Session.Add("oauthProvider", "facebook");
            Session.Add("OauthIdTOUserName", new Hashtable());
            Session.Add("OauthIdTOProvider", new Hashtable());
            Session.Add("OauthPlusProviderIdTOIcon", new Hashtable());
            FormsAuthentication.SetAuthCookie(oauthID, false);

            return Redirect(Url.Action("Index", "Secure"));

        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult oauth2callbackWeSpot(string param)
        {
            //https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.1#confirm
            //https://developers.facebook.com/apps/1409686772621514/app-details/
            //wespottest
            //App ID : 1409686772621514
            //App Secret : c727ce18349262d24c091f8aae5a70b0

            string authToken = Request.Url.Query.Substring(Request.Url.Query.IndexOf("code=") + 5, Request.Url.Query.Length - (Request.Url.Query.IndexOf("code=") + 5));
            //Request.Url.Query.Substring(Request.Url.Query.IndexOf("code=") + 5, Request.Url.Query.IndexOf("scope=") - (Request.Url.Query.IndexOf("code=") + 6));

            // OpenAuth.RequestAuthentication(provider, Url.Action("ExternalLoginCallback"));
            //?client_id=&redirect_uri=http://ibl.exactls.com/Account/ExternalLoginCallback&client_secret=&code=" + authToken;
            string requestUrl = "https://wespot-arlearn.appspot.com/oauth/token";

            //?code=" + authToken + "&client_id=392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com" + "&client_secret=IPLjbx9AmTrO4BGLq0GW-5nH" + "&grant_type=authorization_code" + "&redirect_uri=http://ibl.exactls.com/Account/oauth2callback";


            //scope=email%20profile&state=%2Fprofile&redirect_uri=http://ibl.exactls.com/Account/oauth2callback&response_type=code&client_id=392595925243-k9e1o52oiqjff0i0h4keenj21tftt72b.apps.googleusercontent.com&approval_prompt=force&include_granted_scopes=true";


            RestClient rc = new RestClient();
            RestRequest request = new RestRequest(requestUrl, Method.GET);
            request.AddParameter("code", authToken, ParameterType.GetOrPost);
            request.AddParameter("client_id", "313313", ParameterType.GetOrPost);
            request.AddParameter("client_secret", "01313010131301", ParameterType.GetOrPost);
            //request.AddParameter("grant_type", "authorization_code", ParameterType.GetOrPost);
            request.AddParameter("redirect_uri", "http://ibl.exactls.com/Account/oauth2callbackWeSpot", ParameterType.GetOrPost);
            request.AddParameter("scope", "profile+email", ParameterType.GetOrPost);
            
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            request.RequestFormat = DataFormat.Json;

            //send the request, and check the response.
            RestResponse restResponse = (RestResponse)rc.Execute(request);
            if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }


            //access_token={access-token}&expires={seconds-til-expiration}
            //string access_token = restResponse.Content.Substring(restResponse.Content.IndexOf("access_token=") + 13, restResponse.Content.IndexOf("&expires=") - 13);
            JObject o = JObject.Parse(restResponse.Content);
            string access_token = (string)o["access_token"];
            //string expires_in = (string)o["expires"];
            //string token_type = (string)o["token_type"];


            //client_id= 313313
            //&
            //redirect_uri=http://ibl.exactls.com/Account/ExternalLoginCallback
            //&
            //client_secret=01313010131301
            //&
            //code=a6c8cd5f61c5916a2ad36a3cdf26968";


            string requestUrl1 = "https://wespot-arlearn.appspot.com/oauth/resource_query?access_token=" + access_token;
                //+ access_token;



            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(requestUrl1);
            myReq.ContentType = "text/html";
            WebResponse response = myReq.GetResponse();

            Stream dataStream = response.GetResponseStream();
            StreamReader objReader = new StreamReader(dataStream);

            string sLine = "";
            int i = 0;
            StringBuilder s = new StringBuilder();
            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                s.Append(sLine);
            }
            
            dataStream.Close();
            
            //RestClient rc1 = new RestClient();
            //RestRequest request1 = new RestRequest(requestUrl1, Method.GET);
            //request1.AddParameter("access_token", access_token, ParameterType.GetOrPost);

            //request1.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            //request1.AddHeader("Content-Type", "multipart/form-data");

            //request1.AddHeader("Accept", "text/html");
            //request1.AddHeader("Accept", "application/xhtml+xml");
            //request1.AddHeader("Accept", "application/xml;q=0.9");
            //request1.AddHeader("Accept", "image/webp;q=0.8");


            //request1.AddHeader("Content-Type", "text/html");
            //request1.AddHeader("Content-Type", "application/xhtml+xml");
            //request1.AddHeader("Content-Type", "application/xml;q=0.9");
            //request1.AddHeader("Content-Type", "image/webp;q=0.8");

            //request1.AddHeader("Content-Type", "text/html");
            //request1.AddHeader("Content-Type", "application/xhtml+xml");
            //request1.AddHeader("Content-Type", "application/xml");
            //request1.AddHeader("Content-Encoding", "gzip");
            //request1.AddHeader("Content-Encoding", "gzip");
            //request1.AddHeader("Accept-Encoding", "deflate");
            //request1.RequestFormat = DataFormat.Xml;
            //request1.RequestFormat = DataFormat.Json;
            //send the request, and check the response.
            //RestResponse restResponse1 = (RestResponse)rc1.Execute(request1);
            //if (!restResponse1.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

            /*
             { "id": "stefaan.ternier", "name": "Stefaan Ternier", "email": "stefaan.ternier@gmail.com", "given_name": "Stefaan", "family_name": "Ternier", "picture": "https:\/\/lh3.googleusercontent.com\/-rRb8mSKLrNY\/AAAAAAAAAAI\/AAAAAAAANG8\/C9M5LCAC4GU\/photo.jpg" }
             */


            JObject o1 = JObject.Parse(s.ToString());
            string oauthID = (string)o1["id"];
            string UserName = (string)o1["name"];

            Session.Add("UserName", UserName);
            Session.Add("ProviderUserId", oauthID);
            Session.Add("Provider", "wespot");
            Session.Add("oauthID", oauthID);
            Session.Add("oauthProvider", "wespot");
            Session.Add("OauthIdTOUserName", new Hashtable());
            Session.Add("OauthIdTOProvider", new Hashtable());
            Session.Add("OauthPlusProviderIdTOIcon", new Hashtable());
            FormsAuthentication.SetAuthCookie(oauthID, false);

            return Redirect(Url.Action("Index", "Secure"));

        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult oauth2callbackAccessToken(string param)
        {
            return null;
        }
        
        public ActionResult ExternalLoginCallback1(string url)
        {
            var result = OpenAuth.VerifyAuthentication(Url.Action("ExternalLoginCallback"));
            var result1 = OpenAuth.GetAccountsForUser(result.ProviderUserId);
            /*
            token = flow.ExchangeCodeForTokenAsync("", "AItOawm0U1D4oB2ozJSX8g8KCKeiVZXrPj2QTjE", "postmessage",CancellationToken.None).Result;

            TokenResponse response = null;

            // Use the code exchange flow to get an access and refresh token.
            IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GetClientConfiguration().Secrets,
                    Scopes = new string[] { PlusService.Scope.PlusLogin }
                });
            TokenResponse response = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // response.accessToken now should be populated

            //https://developers.google.com/+/quickstart/csharp
            IAuthorizationCodeFlow flow =
                        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                        {
                            ClientSecrets = secrets,
                            Scopes = new string[] { PlusService.Scope.PlusLogin }
                        });


            //TokenResponse response = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // response.accessToken now should be populated


            GetCredentials(this, CancellationToken.None);

            */

            //token = flow.ExchangeCodeForTokenAsync("", "AItOawm0U1D4oB2ozJSX8g8KCKeiVZXrPj2QTjE", "postmessage",
             //       CancellationToken.None).Result;

            // Create an authorization state from the returned token.
            //context.Session["authState"] = token;

            // Get tokeninfo for the access token if you want to verify.
            /*
            Oauth2Service service = new Oauth2Service(
                new Google.Apis.Services.BaseClientService.Initializer());
            Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
            request.AccessToken = "AItOawm0U1D4oB2ozJSX8g8KCKeiVZXrPj2QTjE";// token.AccessToken;

            Tokeninfo info = request.Execute();

            string gplus_id = info.UserId;
            */




            /*
            
            var result = OpenAuth.VerifyAuthentication(Url.Action("ExternalLoginCallback"));

        //https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token
        //https://www.googleapis.com/plus/v1/people/me?access_token=AItOawm0U1D4oB2ozJSX8g8KCKeiVZXrPj2QTjE
            string requestUrl = "https://www.googleapis.com/auth/plus.login";
            RestClient rc = new RestClient();
            RestRequest request = new RestRequest(requestUrl, Method.GET);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("x-li-format", "json");
            request.RequestFormat = DataFormat.Json;

            //send the request, and check the response.
            RestResponse restResponse = (RestResponse)rc.Execute(request);
            if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; }

            if (result.IsSuccessful == false || result.ProviderUserId == null || result.Provider==null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (result.Provider.Equals("google"))
            {
                IndexAsync(new CancellationToken());
            }

            // this is just demo. Make all things you need before setting cookies
            //FormsAuthentication.SetAuthCookie(result.UserName, false);

            // We need to get the url user has entered to the browser to use it in the redirect. 
            // This is just demo.
            
            Session.Add("UserName", result.UserName);
            Session.Add("ProviderUserId", result.ProviderUserId);
            Session.Add("Provider", result.Provider);
            Session.Add("oauthID", result.ProviderUserId);
            Session.Add("oauthProvider", result.Provider);
            FormsAuthentication.SetAuthCookie(result.UserName,false );
               */
            return Redirect(Url.Action("Index", "Secure"));
        }

        public  void IndexAsync(CancellationToken cancellationToken)
        {
            var result = new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

        }


        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
